
source $VIMRUNTIME/vimrc_example.vim
" source $VIMRUNTIME/mswin.vim
if (has("win32") || has("win32unix"))
    behave mswin
    vnoremap <BS>       d
    vnoremap <C-X>      "+x
    vnoremap <S-Del>    "+x
    vnoremap <C-C>      "+y
    vnoremap <C-Insert> "+y
    map      <C-V>      "+gP
    map      <S-Insert> "+gP
    cmap     <C-V>      <C-R>+
    cmap     <S-Insert> <C-R>+
    exe 'inoremap <script> <C-V>' paste#paste_cmd['i']
    exe 'vnoremap <script> <C-V>' paste#paste_cmd['v']
    imap     <S-Insert> <C-V>
    vmap     <S-Insert> <C-V>
    noremap  <C-Q>      <C-V>
endif
" Use CTRL-S for saving, also in Insert mode
noremap <C-S>   :update<CR>
vnoremap <C-S>  <C-C>:update<CR>
inoremap <C-S>  <C-O>:update<CR>

if (has("win32") || has("win32unix"))
    set diffexpr=MyDiff()
    function! MyDiff()
        let opt = '-a --binary '
        if &diffopt =~ 'icase' | let opt = opt . '-i ' | endif
        if &diffopt =~ 'iwhite' | let opt = opt . '-b ' | endif
        let arg1 = v:fname_in
        if arg1 =~ ' ' | let arg1 = '"' . arg1 . '"' | endif
        let arg2 = v:fname_new
        if arg2 =~ ' ' | let arg2 = '"' . arg2 . '"' | endif
        let arg3 = v:fname_out
        if arg3 =~ ' ' | let arg3 = '"' . arg3 . '"' | endif
        let eq = ''
        if $VIMRUNTIME =~ ' '
            if &sh =~ '\<cmd'
                let cmd = '""' . $VIMRUNTIME . '\diff"'
                let eq = '"'
            else
                let cmd = substitute($VIMRUNTIME, ' ', '" ', '') . '\diff"'
            endif
        else
            let cmd = $VIMRUNTIME . '\diff'
        endif
        silent execute '!' . cmd . ' ' . opt . arg1 . ' ' . arg2 . ' > ' . arg3 . eq
    endfunction
endif

" multi-encoding setting
if has("multi_byte")
    " When 'fileencodings' starts with 'ucs-bom', don't do this manually
    " set bomb
    set fileencodings=ucs-bom,utf-8,cp936,gb18030,taiwan,japan,korea,ucs-2le,latin1
    " CJK environment detection and corresponding setting
    if v:lang =~ "^zh_CN"
        " Simplified Chinese, on Unix euc-cn, on MS-Windows cp936
        set encoding=cp936
        set termencoding=cp936
        if &fileencoding == ''
            set fileencoding=cp936
        endif
    elseif v:lang =~ "^zh_TW"
        " Traditional Chinese, on Unix euc-tw, on MS-Windows cp950
        set encoding=taiwan
        set termencoding=taiwan
        if &fileencoding == ''
            set fileencoding=taiwan
        endif
    elseif v:lang =~ "^ja_JP"
        " Japanese, on Unix euc-jp, on MS-Windows cp932
        set encoding=japan
        set termencoding=japan
        if &fileencoding == ''
            set fileencoding=japan
        endif
    elseif v:lang =~ "^ko"
        " Korean on Unix euc-kr, on MS-Windows cp949
        set encoding=korea
        set termencoding=korea
        if &fileencoding == ''
            set fileencoding=korea
        endif
    endif
    " Detect UTF-8 locale, and override CJK setting if needed
    if v:lang =~ "utf8$" || v:lang =~ "UTF-8$"
        set encoding=utf-8
        set termencoding=utf-8
        set fileencoding=utf-8
    endif
else
    echoerr 'Sorry, this version of (g)Vim was not compiled with "multi_byte"'
endif

if (&encoding == "utf-8") && (has("win32") || has("win32unix"))
    set langmenu=zh_CN.UTF-8            " 设置菜单语言
    language messages zh_CN.UTF-8       " 设置提示信息语言
    source $VIMRUNTIME/delmenu.vim      " 导入删除菜单脚本，删除乱码的菜单
    source $VIMRUNTIME/menu.vim         " 导入正常的菜单脚本
endif

" 设置参数部分
set background=dark
set backspace=indent,eol,start
set helplang=cn
set history=500
set nomodeline
set printoptions=paper:a4
set suffixes=.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.blg,.brf,.cb,.ind,.idx,.ilg,.inx,.out,.toc
set dir=~/.vim_swp
set number
set completeopt=longest,menu
set magic
set ruler
set showmatch
set ambiwidth=double
if has("gui_gtk2")
    set guifont=Inconsolata\ 14,DejaVu\ Sans\ Mono\ 10
else
    set guifont=Inconsolata:h14,DejaVu\ Sans\ Mono:h10,Consolas:h13,Fixedsys:h10
endif

" 打开大于10M的文件时，优化速度
if !exists("my_auto_commands_loaded")
    let my_auto_commands_loaded = 1
    let g:LargeFile = 1024 * 1024 * 10
    augroup LargeFile
        :autocmd BufReadPre * let f=expand("<afile>") | if getfsize(f) > g:LargeFile | set eventignore+=FileType | setlocal noswapfile bufhidden=unload buftype=nowrite undolevels=-1 | else | set eventignore-=FileType | endif
    augroup END
endif

" 折叠相关
set foldcolumn=1
autocmd Syntax c,cpp setlocal foldmethod=syntax
autocmd Syntax c,cpp normal zR

" 搜索相关
set hlsearch
set incsearch
set ignorecase
set smartcase
" vimgrep/lvimgrep(lv)
" 在当前文件中快速查找光标下的单词, 并在窗口的位置列表中显示。:lcl或者,ll关闭 
nmap ,lv :lv /<C-R>=expand("<cword>")<CR>/j %<CR>:lopen<CR>

" 缩进相关
set shiftwidth=4
set softtabstop=4
autocmd FileType c,cpp set expandtab shiftwidth=2 softtabstop=2
set autoindent
set smartindent
set cindent
set cino=:0,g0,(0

" 显示最多行，不用@@
set dy=lastline
" 无菜单、工具栏
" set go=
set nobackup
" 自动切换当前目录为当前文件所在的目录
set autochdir
" 允许在有未保存的修改时切换缓冲区，此时的修改由 vim 负责保存
set hidden
" 显示状态栏 (默认值为 1, 无法显示状态栏)
set laststatus=2
" 设置在状态行显示的信息
set statusline=%<%F[%1*%M%*%n%R%H%W]\ %y[%{&fileformat},%{(&fenc==\"\"?&enc:&fenc).(&bomb?\",BOM\":\"\")}]%=[0x%02B][%{synIDattr(synID(line('.'),col('.'),1),'name')},%{StatusLineRealSyn()}]\ %0(%c%V,%l/%L\ %p%%%)
" Alt组合键不映射到菜单上
set winaltkeys=no

set t_Co=256
if &term == "win32"
    colorscheme darkblue
else
    colorscheme bandit_wst   " 这是我参考desert修改过的bandit，表现如同desert，并且支持256色终端
endif
filetype plugin indent on

" 设置初始窗口大小
" set columns=207
" set lines=55
" maximum the initial window
if (has("win32") || has("win32unix"))
    au GUIEnter * simalt ~x
else
    au GUIEnter * call MaximizeWindow()
endif

function! MaximizeWindow()
    silent !wmctrl -r :ACTIVE: -b add,maximized_vert,maximized_horz
endfunction

" Taglist相关
map <F6> :silent! Tlist<CR>
" noremap <silent> <F6> :TlistUpdate<CR>
let Tlist_Show_One_File=1
let Tlist_Exit_OnlyWindow=1
let Tlist_Use_Right_Window=0

" 在工程中查找，用到了Grep插件，关闭窗口为:ccl或者,ll
" 返回刚才的地方使用`a
nnoremap <silent> <F4> ma:Grep<CR>

" 使用NERDTree插件查看工程文件
nmap <F8> <ESC>:NERDTreeToggle<CR>
" 设置NERDTree子窗口宽度
let NERDTreeWinSize=22
" where NERD tree window is placed on the screen
let NERDTreeWinPos = "right"
" 若最后一个为NERDTree窗口时，可不用再次输入:q
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == 'primary') | q | endif

if 0
" winManager相关
" let g:winManagerWindowLayout = 'FileExplorer|TagList'
" let g:winManagerWidth = 30
" let g:defaultExplorer = 0
" nmap wm :WMToggle<cr>
" nmap <C-W><C-F> :FirstExplorerWindow<cr>
" nmap <C-W><C-B> :BottomExplorerWindow<cr>

" MiniBufExplorer相关
" let g:miniBufExplMapCTabSwitchBufs = 1
" let g:miniBufExplMapWindowNavArrows = 1
" let g:miniBufExplMaxSize = 2
" autocmd FileType c,cpp let g:miniBufExplorerMoreThanOne = 0
" let g:miniBufExplForceSyntaxEnable = 1

" cscope相关
set cscopequickfix=s-,c-,d-,i-,t-,e-
nmap <C-_>s :cs find s <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>g :cs find g <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>c :cs find c <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>t :cs find t <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>e :cs find e <C-R>=expand("<cword>")<CR><CR>
nmap <C-_>f :cs find f <C-R>=expand("<cfile>")<CR><CR>
nmap <C-_>i :cs find i ^<C-R>=expand("<cfile>")<CR>$<CR>
nmap <C-_>d :cs find d <C-R>=expand("<cword>")<CR><CR>

" cscope 和 ctag 调用函数
map <F11> :call Do_CsTag()<CR>
function! Do_CsTag()
    let dir = getcwd()
    if filereadable("tags")
        if(g:iswindows==1)
            let tagsdeleted=delete(dir."\\"."tags")
        else
            let tagsdeleted=delete("./"."tags")
        endif
        if(tagsdeleted!=0)
            echohl WarningMsg | echo "Fail to do tags! I cannot delete the tags" | echohl None
            return
        endif
    endif
    if has("cscope")
        silent! execute "cs kill -1"
    endif
    if filereadable("cscope.files")
        if(g:iswindows==1)
            let csfilesdeleted=delete(dir."\\"."cscope.files")
        else
            let csfilesdeleted=delete("./"."cscope.files")
        endif
        if(csfilesdeleted!=0)
            echohl WarningMsg | echo "Fail to do cscope! I cannot delete the cscope.files" | echohl None
            return
        endif
    endif
    if filereadable("cscope.out")
        if(g:iswindows==1)
            let csoutdeleted=delete(dir."\\"."cscope.out")
        else
            let csoutdeleted=delete("./"."cscope.out")
        endif
        if(csoutdeleted!=0)
            echohl WarningMsg | echo "Fail to do cscope! I cannot delete the cscope.out" | echohl None
            return
        endif
    endif
    if(executable('ctags'))
        silent! execute "!ctags -R --c-types=+p --fields=+lS *"
        " silent! execute "!ctags -R --c++-kinds=+p --fields=+iaS --extra=+q ."
    endif
    if(executable('cscope') && has("cscope") )
        if(g:iswindows!=1)
            silent! execute "!find . -name '*.h' -o -name '*.c' -o -name '*.cpp' -o -name '*.java' -o -name '*.cs' > cscope.files"
        else
            silent! execute "!dir /s/b *.c,*.cpp,*.h,*.java,*.cs >> cscope.files"
        endif
        silent! execute "!cscope -b"
        execute "normal :"
        if filereadable("cscope.out")
            execute "cs add cscope.out"
        endif
    endif
    execute "redr!"
endfunction

endif

" 在C语言中加入函数说明注释信息
map ,fg :Dox<cr>
map ,fa :DoxAuthor<cr>
map ,fl :DoxLic<cr>
let g:DoxygenToolkit_startCommentTag = "/*******************************************************************************"
let g:DoxygenToolkit_startCommentBlock = g:DoxygenToolkit_startCommentTag
let g:DoxygenToolkit_endCommentTag = "******************************************************************************/"
let g:DoxygenToolkit_endCommentBlock = g:DoxygenToolkit_endCommentTag
let s:licenseTag = "Copyright (C), 2008-2011, Wst.  "
let s:licenseTag = s:licenseTag . "All right reserved"
let g:DoxygenToolkit_licenseTag = s:licenseTag
let g:DoxygenToolkit_authorName="Sitao Wang, wangsitao0004@163.com"
let g:DoxygenToolkit_fileTag = "   File:\t"
let g:DoxygenToolkit_authorTag = " Author:\t"
let g:DoxygenToolkit_versionTag = "Version:\t"
let g:DoxygenToolkit_dateTag = "   Date:\t"
let g:DoxygenToolkit_undocTag="DOXIGEN_SKIP_BLOCK"
let g:DoxygenToolkit_briefTag_pre = "   Desc:\t"
let g:DoxygenToolkit_paramTag_pre = "  Param:\t"
let g:DoxygenToolkit_returnTag = " Return:\t"
let g:DoxygenToolkit_briefTag_funcName = "no"
let g:DoxygenToolkit_maxFunctionProtoLines = 30

" 在vim中调用source insight打开对应文件，windows系统中才生效
if (has("win32") || has("win32unix"))
    nnoremap <silent>  <F12> :!start Insight3 -i +<C-R>=expand(line("."))<CR> "%"<CR>
endif

" 快速注释相关
map <c-h> ,c<space>
let NERDSpaceDelims=1       " 注释后空一格
let NERDCompactSexyComs=0   " 使用*/在前面的性感注释
let NERD_c_alt_style=1      " 对C语言使用//注释符

" 取消查找高亮
nnoremap <C-l> :noh<CR><C-l>
:map     ,m    *N
:map     Y     y$

" 在插入模式下移动光标
" set winaltkeys=no 后将不会和windows的菜单栏冲突
imap <A-h> <Left>
imap <A-l> <Right>
imap <A-k> <Up>
imap <A-j> <Down>

imap jj    <Esc>

" 在输入模式下，括号自动补全
" :inoremap ( ()<ESC>:let leavechar=")"<CR>i
" :inoremap ) <c-r>=ClosePair(')')<CR>
" :inoremap [ []<ESC>:let leavechar="]"<CR>i
" :inoremap ] <c-r>=ClosePair(']')<CR>
" :inoremap { {}<ESC>:let leavechar="}"<CR>i
" :inoremap } <c-r>=ClosePair('}')<CR>

" 在C语言中对一些符号自动补全
" autocmd FileType c,cpp :inoremap ' ''<ESC>:let leavechar="'"<CR>i
" autocmd FileType c,cpp :inoremap " ""<ESC>:let leavechar="\""<CR>i
" autocmd FileType c,cpp :inoremap , , 
" autocmd FileType c,cpp :inoremap ( (  )<ESC>:let leavechar=")"<CR>hi
autocmd FileType c,cpp :inoremap { <c-r>=ClsoeBrace()<CR>

function! ClosePair(char)
    if getline('.')[col('.') - 1] == a:char
        return "\<Right>"
    else
        return a:char
    endif
endfunction

function! ClsoeBrace()
    if getline('.')[col('.') - 2] == '='
        return "{  }\<ESC>:let leavechar=\"}\"\<CR>hi"
    elseif getline('.')[col('.') - 3] == '='
        return "{  }\<ESC>:let leavechar=\"}\"\<CR>hi"
    elseif getline('.')[col('.') - 1] == '{'
        return "{  }\<ESC>:let leavechar=\"}\"\<CR>hi"
    elseif getline('.')[col('.') - 2] == '{'
        return "{  }\<ESC>:let leavechar=\"}\"\<CR>hi"
    elseif getline('.')[col('.') - 3] == '{'
        return "{  }\<ESC>:let leavechar=\"}\"\<CR>hi"
    elseif getline('.')[col('.') - 2] == ','
        return "{  }\<ESC>:let leavechar=\"}\"\<CR>hi"
    elseif getline('.')[col('.') - 3] == ','
        return "{  }\<ESC>:let leavechar=\"}\"\<CR>hi"
    else
        return "{\<ENTER>}\<ESC>:let leavechar=\"}\"\<CR>O"
    endif
endfunction

" 快捷的到括号外，错行型括号不能用
" :imap <C-l> <Esc>:exec 'normal f' .leavechar<CR>a

" 在可视模式下，现有的文字添加成对符号
if &selection == "exclusive"
    :vnoremap   (    <Esc>`>i)<Esc>`<i(<Esc>
    :vnoremap   {    <Esc>`>o}<Esc>`<O{<Esc>
    :vnoremap   [    <Esc>`>i]<Esc>`<i[<Esc>
    :vnoremap   ""   <Esc>`>i"<Esc>`<i"<Esc>
    :vnoremap   ''   <Esc>`>i'<Esc>`<i'<Esc>
else
    :vnoremap   (    <Esc>`>a)<Esc>`<i(<Esc>
    :vnoremap   {    <Esc>`>o}<Esc>`<O{<Esc>
    :vnoremap   [    <Esc>`>a]<Esc>`<i[<Esc>
    :vnoremap   ""   <Esc>`>a"<Esc>`<i"<Esc>
    :vnoremap   ''   <Esc>`>a'<Esc>`<i'<Esc>
endif

if 0
" 代码的大括号风格整理,将黎风格转为涛风格,对于//注释,还不完美
autocmd FileType c,cpp :noremap <silent> ,ict :call Li_to_Tao()<CR>
" 助记：Indent Convert to Tao
function! Li_to_Tao()
    silent! execute "g#\\\\s*$#s/}/QzjjAjZZ/ge"
    silent! execute "g#\\\\s*$#s/{/JUmMqAzj/ge"
    silent! execute "%s#\\(//.*\\){#\\1ZVQQzjmN#ge"
    silent! execute "%s#\\(//.*\\)}#\\1YZQMJJqz#ge"
    silent! execute "g#)\\s*{#normal f{i\<CR>"
    silent! execute "g#\\<do\\>\\s*{#normal f{i\<CR>\<ESC>"
    silent! execute "g#\\<else\\>\\s*{#normal f{i\<CR>\<ESC>"
    silent! execute "g#}\\s*\\<else\\>#normal f}a\<CR>\<ESC>"
    silent! execute "g#[^ ,=]\\s*{\\s*[^ /\"']#normal f{F{a\<CR>\<ESC>"
    silent! execute "g#^\\s*{\\s*[^ /\"']#normal f{F{a\<CR>\<ESC>"
    silent! execute "g#;\\s*}#normal $F}i\<CR>\<ESC>"
    silent! execute "g#}\\s*}\\s*[^;]#normal $F}i\<CR>\<ESC>"
    silent! execute "%s#ZVQQzjmN#{#ge"
    silent! execute "%s#YZQMJJqz#}#ge"
    silent! execute "%s/QzjjAjZZ/}/ge"
    silent! execute "%s/JUmMqAzj/{/ge"
    silent! execute "%s/\\s*$//ge"
    " normal gg=G
endfunction

" 代码的大括号风格整理,将涛风格转为黎风格,对于//注释,还不完美
" 助记：Indent Convert to Li
autocmd FileType c,cpp :noremap <silent> ,icl :call Tao_to_Li()<CR>
function! Tao_to_Li()
    silent! execute "g#//#normal AxXxQZAqzjU\<ESC>"
    silent! execute "g#\\\\s*$#normal AxXxQZAqzjU\<ESC>"
    silent! execute "%s/)\\s*\\n\\s\\+{/) {/ge"
    silent! execute "%s/\\<do\\>\\s*\\n\\s\\+{/do {/ge"
    silent! execute "%s/\\<else\\>\\s*\\n\\s\\+{/else {/ge"
    silent! execute "%s#)\\s*\\(//.*\\)\\n\\s\\+{\\s*$#) { \\1#ge"
    silent! execute "%s#\\<do\\>\\s*\\(//.*\\)\\n\\s\\+{\\s*$#do { \\1#ge"
    silent! execute "%s#\\<else\\>\\s*\\(//.*\\)\\n\\s\\+{\\s*$#else { \\1#ge"
    silent! execute "%s/}\\s*\\n\\s*\\<else\\>/} else/ge"
    silent! execute "%s#xXxQZAqzjU##ge"
    silent! execute "%s#xXxQZAqzjU##ge"
    " normal gg=G
endfunction

" C 语言格式整理，由于不能区别注释，以及字符串，所以不推荐使用
    autocmd FileType c,cpp :nnoremap <silent> ,tf :call My_Format()<CR>
    function! My_Format()
        silent! execute "%s/\\(\\w\\|]\\|)\\)+\\(\\w\\|(\\)/\\1 + \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)\\*\\(\\w\\|(\\)/\\1 \\* \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)%\\(\\w\\|(\\)/\\1 % \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)>\\(\\w\\|(\\)/\\1 > \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)<\\(\\w\\|(\\)/\\1 < \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)==\\(\\w\\|(\\)/\\1 == \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)!=\\(\\w\\|(\\)/\\1 != \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)<=\\(\\w\\|(\\)/\\1 <= \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)>=\\(\\w\\|(\\)/\\1 >= \\2/ge"
        silent! execute "%s#\\(\\w\\|]\\|)\\)\\zs&&\\ze\\(\\w\\|(\\)# \& #ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)||\\(\\w\\|(\\)/\\1 || \\2/ge"
        silent! execute "%s#\\(\\w\\|]\\|)\\)\\zs&\\ze\\(\\w\\|(\\)# \& #ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)|\\(\\w\\|(\\)/\\1 | \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)^\\(\\w\\|(\\)/\\1 ^ \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)<<\\(\\w\\|(\\)/\\1 << \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\)>>\\(\\w\\|(\\)/\\1 >> \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)=\\(\\w\\|(\\)/\\1 = \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)+=\\(\\w\\|(\\)/\\1 += \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)-=\\(\\w\\|(\\)/\\1 -= \\2/ge"
        silent! execute "%s#\\(\\w\\|]\\)/=\\(\\w\\|(\\)#\\1 /= \\2#ge"
        silent! execute "%s/\\(\\w\\|]\\)\\*=\\(\\w\\|(\\)/\\1 \\*= \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)%=\\(\\w\\|(\\)/\\1 %= \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)|=\\(\\w\\|(\\)/\\1 |= \\2/ge"
        silent! execute "%s#\\(\\w\\|]\\)\\zs&=\\ze\\(\\w\\|(\\)# \& #ge"
        silent! execute "%s/\\(\\w\\|]\\)^=\\(\\w\\|(\\)/\\1 ^= \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)>>=\\(\\w\\|(\\)/\\1 >>= \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)<<=\\(\\w\\|(\\)/\\1 <<= \\2/ge"
        silent! execute "%s/,\\(\\S\\)/, \\1/ge"
        silent! execute "%s/;\\(\\S\\)/; \\1/ge"
        silent! execute "%s/\\zs(\\ze\\(\\S\\)/\& /ge"
        silent! execute "%s/\\(\\S\\)\\zs)\\ze/ \&/ge"
        silent! execute "%s/(\\s\\+)/()/ge"
        silent! execute "%s/\\zs(\\s\\+\\ze(/(/ge"
        silent! execute "%s/)\\zs\\s\\+)\\ze/)/ge"
        silent! execute "%s/)\\zs\\s\\+)\\ze/)/ge"
        silent! execute "%s/\\zs{\\ze\\(\\w\\|{\\|(\\)/\& /ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\|}\\)\\zs}\\ze/ \&/ge"
        silent! execute "%s/\\(\\w\\|]\\|)\\|}\\)\\zs}\\ze/ \&/ge"
        silent! execute "%s/\\zs}\\ze\\(\\w\\)/\& /ge"
        silent! execute "%s/\\(\\w\\|]\\)= \\(\\w\\|(\\)/\\1 = \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\) =\\(\\w\\|(\\)/\\1 = \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)=\\(\\'\\)/\\1 = \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\) =\\(\\'\\)/\\1 = \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)= \\(\\'\\)/\\1 = \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)=\\(\"\\)/\\1 = \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\)= \\(\"\\)/\\1 = \\2/ge"
        silent! execute "%s/\\(\\w\\|]\\) =\\(\"\\)/\\1 = \\2/ge"
    endfunction
endif

" 使用indent程序整理C语言代码
autocmd FileType c,cpp :nnoremap <silent> ,it :call My_indent()<CR>
function! My_indent()
    if (has("unix"))    " 在unix系统中，将文中的^M删除，统一为unix换行，使indent更准确
        silent! execute "set ff=unix"
    endif
    silent! execute "%s/[\x0d]$//ge"
    silent! execute "%s/[\x0d]/\r/ge"
    if 0       " 括号内加空白，但相连的括号不加
        silent! execute "%!indent -npro -kr -nut -l80 -ss -ncs -bl -nce -bli0 -nsaf -nsai -nsaw -bls -prs -cbi0"
        silent! execute "%s/(\\s\\+)/()/ge"
        silent! execute "%s/\\zs(\\s\\+\\ze(/(/ge"
        silent! execute "%s/)\\zs\\s\\+)\\ze/)/ge"
        silent! execute "%s/)\\zs\\s\\+)\\ze/)/ge"
        silent! execute "norm Go\<CR>\<CR>\<ESC>"
    else       " 括号内不加空白
        silent! execute "%!indent -npro -kr -nut -l180 -ss -ncs -bl -nce -bli0 -nsaf -nsai -nsaw -bls -cbi0"
        silent! execute "norm Go\<CR>\<CR>\<ESC>"
    endif
endfunction

autocmd FileType c,cpp :nnoremap <silent> ,il :call Li_indent()<CR>
function! Li_indent()
    if (has("unix"))    " 在unix系统中，将文中的^M删除，统一为unix换行，使indent更准确
        silent! execute "set ff=unix"
    endif
    silent! execute "%s/[\x0d]$//ge"
    silent! execute "%s/[\x0d]/\r/ge"
    silent! execute "%!indent -npro -kr -nut -i2 -l180 -ss -ncs -cbi0"
    silent! execute "%s/\\(^\\s\\+return\\)\\s*/\\1  /ge"
    silent! execute "norm Go\<CR>\<CR>\<ESC>"
endfunction

" 使用Tabularize来控制对齐，这里只针对= 和 :
" 完整的使用方式是:Tab /{需要的符号}
if !exists(":Tabularize")
    nmap ,a= :Tabularize /=<CR>
    vmap ,a= :Tabularize /=<CR>
    nmap ,a: :Tabularize /:\zs<CR>
    vmap ,a: :Tabularize /:\zs<CR>
    nmap ,aa :Tabularize /
    vmap ,aa :Tabularize /
endif

" 使用Tabularize功能，实现 | 在insert模式下动态对齐
inoremap <silent> <Bar>   <Bar><Esc>:call <SID>align()<CR>a
function! s:align()
    let p = '^\s*|\s.*\s|\s*$'
    if exists(':Tabularize') && getline('.') =~# '^\s*|' && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
        let column = strlen(substitute(getline('.')[0:col('.')],'[^|]','','g'))
        let position = strlen(matchstr(getline('.')[0:col('.')],'.*|\s*\zs.*'))
        Tabularize/|/l1
        normal! 0
        call search(repeat('[^|]*|',column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
    endif
endfunction

" Use ,ss for saving, 并且使用cp936编码保存
noremap ,ss     :set fileencoding=cp936<CR>:w<CR>
" Use ,su for saving, 并且使用utf-8编码保存
noremap ,su     :set fileencoding=utf-8<CR>:w<CR>
" saving as root
noremap ,sr     :%!sudo tee %<CR>

" 转换换行符
" 助记：Fileformat Dos     Fileformat Unix
noremap ,fd     :set ff=dos<CR>:%s/\r\+$//e<CR>
noremap ,fu     :set ff=unix<CR>:%s/\r\+$//e<CR>

" TxtBrowser相关
au BufEnter *.txt setlocal ft=txt

" statusline相关
function! StatusLineRealSyn()
    let synId = synID(line('.'),col('.'),1)
    let realSynId = synIDtrans(synId)
    if synId == realSynId
        return 'Normal'
    else
        return synIDattr( realSynId, 'name' )
    endif
endfunction

" man.vim 相关。查看帮助的技巧：\K
autocmd Filetype c,cpp :so $VIMRUNTIME/ftplugin/man.vim
if (has("unix"))
    nmap ,k :Man 3 <cword><CR>
endif

" quickbuf 相关
let g:qb_hotkey = "<F2>" 

" tagbar 相关
nnoremap <silent> <F7> :TagbarToggle<CR>
" 设置tagbar子窗口的位置出现在主编辑区的左边
let tagbar_left = 1
" 设置标签子窗口的宽度
let tagbar_width = 25
" 按代码中的顺序排列标签
let tagbar_sort = 0

" 我的C/C++代码标识
autocmd Filetype c,cpp nnoremap ,w :call Comment_of_me()<CR>
function! Comment_of_me()
    let date_today = strftime("%Y.%m.%d")
    let comment_string = "//\<Space>WangST-".date_today
    silent! execute "norm "."A\<Tab>".comment_string."\<ESC>"
    unlet date_today
    unlet comment_string
endfunction

" 快捷输入日期和时间
:inoremap   <unique>    <leader>cd      <C-R>=strftime("%Y-%m-%d")<CR>
:inoremap   <unique>    <leader>ct      <C-R>=strftime("%H:%M:%S")<CR>
:inoremap   <unique>    <leader>cf      <C-R>=strftime("%Y-%m-%d %H:%M:%S")<CR>

" code_complete 相关
autocmd Filetype c,cpp let g:completekey="<C-J>"

" ctags_highlighting
if ! exists('g:TagHighlightSettings')
    let g:TagHighlightSettings = {}
endif
let g:TagHighlightSettings['DoNotGenerateTags']=1
let g:TagHighlightSettings['TagFileDirectory']=$HOME.'/.indexer_files_tags'
let g:TagHighlightSettings['TagFileName']=substitute(getcwd(), "[\\/:]", "_", "g")
let g:TagHighlightSettings['TypesFileDirectory']=$HOME.'/.indexer_files_tags'
let g:TagHighlightSettings['TypesFilePrefix']=substitute(getcwd(), "[\\/:]", "_", "g")
nnoremap <silent> <F5> :w<CR>:UpdateTypesFileOnly<CR>

" indexer
let g:indexer_ctagsJustAppendTagsAtFileSave=0

" neocomplcache
let g:neocomplcache_enable_at_startup=1
map <silent> ,nc :let g:neocomplcache_disable_auto_complete=!g:neocomplcache_disable_auto_complete<CR>
let g:neocomplcache_disable_auto_complete=1
autocmd Filetype c,cpp normal ,nc

" 一键make
nmap ,rm  :wa<CR>:make<CR>:cw<CR><CR>
nmap ,rs  :wa<CR>:make static<CR>:cw<CR><CR>
nmap ,rd  :wa<CR>:make dynatic<CR>:cw<CR><CR>
nmap ,rc :make clean<CR><CR>
" 关闭quickfix窗口
nmap ,ll :ccl<CR>:lcl<CR>

" 手动添加libmp的tags
" 助记：Tags libMp
autocmd Filetype c,cpp map ,tm :set tags+=$HOME/.indexer_files_tags/libmp<CR>

" 手动添加/usr/include的tags
" 助记：Tags Include Add         Tags Include Subtract 
autocmd Filetype c,cpp map ,tia :set tags+=$HOME/.indexer_files_tags/include<CR>
autocmd Filetype c,cpp map ,tis :set tags-=$HOME/.indexer_files_tags/include<CR>

if !has("gui_running")
    set mouse=nv
endif

" 十六进制切换
nnoremap ,xx :%!xxd<CR>
nnoremap ,xr :%!xxd -r<CR>

" vimwiki
let g:vimwiki_use_mouse = 1
let g:vimwiki_list = [{'path': 'E:/wangsitao/vimwiki/',
    \ 'path_html': 'E:/wangsitao/vimwiki/html/',
    \ 'html_header': 'E:/wangsitao/vimwiki/template/header.tpl',}] 


